package com.example.demo.util;

import com.alibaba.dubbo.config.annotation.Service;
import com.example.demo.api.EmailMessageService;
import com.example.demo.vo.EmailMessageVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by Hy on 2018/8/6.
 */
@Service
public class EmailJob {
    private static final Logger logger = LoggerFactory.getLogger(EmailJob.class);
    @Autowired
    private EmailMessageService emailMessageService;
    @Autowired
    private TaskExecutor taskExecutor;

    public void sendEmail(){
        List<EmailMessageVo> emailMessageVoList = emailMessageService.scanForSending();
        logger.info("查询到{}条数据需要发送邮件",emailMessageVoList.size());
        for (int i =0;i<emailMessageVoList.size();i++){
            EmailMessageVo emailMessageVo = emailMessageVoList.get(i);
            taskExecutor.execute(new SingleEmailRunnable(emailMessageVo));
        }
    }
    private class SingleEmailRunnable implements Runnable{
        private EmailMessageVo emailMessageVo;

        public SingleEmailRunnable(EmailMessageVo emailMessageVo) {
            this.emailMessageVo = emailMessageVo;
        }

        @Override
        @Transactional(rollbackFor ={Exception.class,RuntimeException.class})
        public void run() {
            //SendEmail.sendMail();
        }
    }
}
